package com.dflc.controller;

import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.req.BackUserReq;
import com.dflc.entity.req.LoginReq;
import com.dflc.entity.vo.LoginUserInfoVo;
import com.dflc.service.TBackLoginUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 登录
 * @author tqx
 * @version 1.0.0.0
 * <p>Title: SysLoginUserController </p >
 * <p>Description: 登录  </p >
 * Copyright: Copyright(c) 产品研发与安全部
 * Date: 2024年11月26日 17:30
 */
@Slf4j
@RestController
@RequestMapping("/sysLoginUser")
public class SysLoginUserController {

    @Resource
    private TBackLoginUserService tBackLoginUserService;



    /**
     * 用户登录
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 用户登录
     * @param req
     * @return HttpResponseEntity<LoginUserInfo>
     */
    @ResponseBody
    @PostMapping(value = "/login")
    public HttpResponseEntity<LoginUserInfoVo> login(@RequestBody LoginReq req, HttpServletRequest request) {
        String clientIp = getClientIp(request);
        return tBackLoginUserService.login(req,clientIp);
    }


    /**
     * 忘记密码
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 忘记密码
     * @param req
     * @return HttpResponseEntity
     */
    @PostMapping("/retrievePassword")
    public HttpResponseEntity retrievePassword(@Valid @RequestBody BackUserReq req) {
        try {
            return  tBackLoginUserService.findUserByUserName(req);
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 对于多级代理的情况，取第一个非unknown的IP
        if (ip != null && ip.contains(",")) {
            ip = ip.split(",")[0];
        }

        return ip;
    }
}
